package com.heima.wemedia.service.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.heima.common.constants.KafkaMessageConstant;
import com.heima.wemedia.service.dao.WmMaterialDao;
import com.heima.wemedia.service.dao.WmNewsDao;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dto.WmNewsDto;
import com.heima.model.wemedia.dto.WmNewsPageReqDto;
import com.heima.model.wemedia.entity.WmMaterial;
import com.heima.model.wemedia.entity.WmNews;
import com.heima.wemedia.service.service.WmNewsService;
import com.heima.wemedia.service.utils.WmThreadLocalUtil;
import com.heima.wemedia.service.dao.WmNewsMaterialDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import com.github.pagehelper.Page;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 自媒体文章表(WmNews)表服务实现类
 *
 * @author makejava
 * @since 2022-04-12 19:20:45
 */
@Service("wmNewsService")
public class WmNewsServiceImpl implements WmNewsService {
    @Resource

    private WmNewsDao wmNewsDao;


    @Resource
    private WmNewsMaterialDao wmNewsMaterialDao;

    @Resource
    private WmMaterialDao wmMaterialDao;

    @Resource
    private KafkaTemplate kafkaTemplate;


    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public WmNews queryById(Long id) {
        return this.wmNewsDao.queryById(id);
    }


    /**
     * 新增数据
     *
     * @param wmNews 实例对象
     * @return 实例对象
     */
    @Override
    public WmNews insert(WmNews wmNews) {
        this.wmNewsDao.insert(wmNews);
        return wmNews;
    }

    /**
     * 修改数据
     *
     * @param wmNews 实例对象
     * @return 实例对象
     */
    @Override
    public WmNews update(WmNews wmNews) {
        this.wmNewsDao.update(wmNews);
        return this.queryById(wmNews.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public ResponseResult deleteById(Long id) {
        //1. 根据ID查询文章详情
        WmNews wmNews = wmNewsDao.queryById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2. 判断文章状态
        if (wmNews.getStatus() == 9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH, "已发布文章不能删除");
        }
        //3. 删除文章数据
        wmNewsDao.deleteById(id);
        //4. 删除文章素材关联数据
        wmNewsMaterialDao.deleteByNewsId(wmNews.getId());

        return ResponseResult.okResult("删除文章成功");
    }

    @Override
    public ResponseResult submit(WmNewsDto dto) {
        //效验参数
        if (dto == null || StringUtils.isBlank(dto.getTitle())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //处理数据
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);

        wmNews.setLabels(dto.getLabels());

        List<String> cover_images = dto.getImages();
        List<String> content_images = extractContentImage(dto.getContent());

        if (dto.getType() == -1) {
            if (content_images.size() >= 3) {
                cover_images = content_images.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(3);
            } else if (content_images.size() > 0 && content_images.size() < 3) {
                cover_images = content_images.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(1);
            } else {
                cover_images = Collections.emptyList();
                wmNews.setType(0);
            }
        }
        wmNews.setImages(StringUtils.join(cover_images.toArray(), ","));//URL1,URL2
        //保存文章信息
        saveWmNews(wmNews);

        saveCoverMatarialRelation(wmNews.getId(), cover_images);
        saveContentMatarialRelation(wmNews.getId(), content_images);
        //发送消息通知审核服务进行文章审核
        kafkaTemplate.send(KafkaMessageConstant.NEWS_AUTO_SCAN_TOPIC,wmNews.getId() +"");

        //封装数据返回
        return ResponseResult.okResult("发布成功");
    }

    @Override
    public ResponseResult list(WmNewsPageReqDto dto) {
        //1. 参数校验
        dto.checkParam();
        //2. 封装查询条件
        Map<String, Object> queryParam = BeanUtil.beanToMap(dto);
        queryParam.put("userId", WmThreadLocalUtil.getUser().getId());

        //3. 执行查询
        PageHelper.startPage(dto.getPage(), dto.getSize());
        //Page<WmNews> page = wmNewsDao.queryByMap(queryParam);
        Page<WmNews> page = wmNewsDao.queryByMap(queryParam);
        //4. 封装数据返回
        ResponseResult result = new PageResponseResult(page.getPageNum(),page.getPageSize(),(int)page.getTotal());
        result.setData(page.getResult());
        return result;
    }

    /**
     * 保存文章和素材的引用关系
     *
     * @param newaId
     * @param images
     * @param type
     */
    private void saveMatarialRelation(Long newaId, List<String> images, int type) {

        if (CollectionUtils.isEmpty(images)) {
            return;
        }
        //保存文章和素材关系
        images = images.stream().distinct().collect(Collectors.toList());

        List<WmMaterial> materialList = wmMaterialDao.queryByUrls(images);

        List<Long> ids = materialList.stream().map(wmMaterial -> wmMaterial.getId()).collect(Collectors.toList());
        if (images.size() != ids.size()) {
            throw new RuntimeException("素材缺失");
        }

        wmNewsMaterialDao.saveNewsRelation(newaId, ids, type);
    }



    /**
     * 保存文章和内容图片的引用关系
     *
     * @param
     * @param content_images
     */
    private void saveContentMatarialRelation(Long newaId, List<String> content_images) {

        saveMatarialRelation(newaId, content_images, 1);
    }


    /**
     * 保存文章和封面图片的引用关系
     *
     * @param newaId
     * @param cover_images
     */
    private void saveCoverMatarialRelation(Long newaId, List<String> cover_images) {
        saveMatarialRelation(newaId, cover_images, 0);
    }

    /**
     * 保存文章信息到数据库
     *
     * @param wmNews
     */
    private void saveWmNews(WmNews wmNews) {
        //1.补全数据
        wmNews.setUserId(Long.valueOf(WmThreadLocalUtil.getUser().getId()));
        wmNews.setEnable(1);
        wmNews.setCreatedTime(new Date());
        wmNews.setUpdatedTime(new Date());

        //2.保存数据库
        if (wmNews.getId() == null) {
            wmNewsDao.insert(wmNews);
            return;
        }
        wmNewsDao.update(wmNews);

        //如果是修改，需要删除文章和素材
        wmNewsMaterialDao.deleteByNewsId(wmNews.getId());
    }


    /**
     * 从文章内容中抽取图片数据
     *
     * @param content
     * @return
     */
    private List<String> extractContentImage(String content) {
        //1.将文章内容转化为java集合

        List<Map> list = JSON.parseArray(content, Map.class);
        //2. 便利获取每一部分数据

        List<String> imageList = list.stream()
                .filter(map -> map.get("type").equals("image"))
                .map(map -> map.get("value").toString())
                .collect(Collectors.toList());
        return imageList;

    }
}
